﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Common.Utilities;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.ETL
{
	/// <summary>
	/// 
	/// </summary>
	public partial class DelimitedTextFileReaderEditor : Form, IComponentEditor
	{
		/// <summary>
		/// 
		/// </summary>
		public DelimitedTextFileReaderEditor()
		{
			InitializeComponent();
		}

		private void DelimitedTextFileReaderEditor_Load(object sender, EventArgs e)
		{
			this.cbo_SpecialDelimiter.Items.Clear();
			for(int i=0;i<=5;i++)
			{
				SpecialDelimiter specialDelimiter = (SpecialDelimiter) i;
				this.cbo_SpecialDelimiter.Items.Add(Enum.GetName(typeof (SpecialDelimiter), specialDelimiter));
			}
		}

		#region Implementation of IComponentEditor
		private object _ActivityNode;
		private DelimitedTextFileReaderComponent _TxtFileReaderComponent;

		public event UpdateComponentSettings UpdateComponentSettingEvent;

		/// <summary></summary>
		public object OwnerActivityNode
		{
			get { return _ActivityNode; }
			set { _ActivityNode=value; }
		}

		/// <summary></summary>
		public Type WorkflowComponentType
		{
			get { return typeof(DelimitedTextFileReaderComponent); }
		}

		/// <summary></summary>
		public void LoadSettings(GlobalVariable[] globalVars, WorkflowComponentBase[] fromComponents, object activityNode, WorkflowComponentBase wfComponent)
		{
			this._ActivityNode = activityNode;
			this._TxtFileReaderComponent = (DelimitedTextFileReaderComponent) wfComponent;

			DelimitedTextFileReaderInstruction instruction =
				(DelimitedTextFileReaderInstruction) this._TxtFileReaderComponent.Instruction;
			this.txt_InputFile.Text = instruction.TxtFilePath;
			this.cbo_SpecialDelimiter.SelectedIndex = (int) instruction.ColumnDelimiter.SpecialDelimiter;
			this.num_ColHeaderRow.Value = instruction.RowNumContainingColumnHeaders;
			this.txt_DelimiterPattern.Text = instruction.ColumnDelimiter.DelimiterPattern;
		    this.txt_Connection.Text = instruction.ConnStr;
		    this.txt_Schema.Text = instruction.SchemaName;
            if (!string.IsNullOrEmpty(instruction.ConnStr))
            {
                this.PopulateTables(instruction.ConnStr, instruction.SchemaName);
                this.SelectComboxValue(this.cbo_Table, instruction.TableName);
            }
		    this.ck_CreateNewTable.Checked = instruction.RecreateTable;
		    this.ck_ClearData.Checked = instruction.ClearExistingData;
		}

	    private void SelectComboxValue(ComboBox comboBox, string name)
	    {
	        if(comboBox.Items.Count>0 && !string.IsNullOrEmpty(name))
	        {
	            for(int i=0;i<comboBox.Items.Count;i++)
	            {
	                if(comboBox.Items[i].ToString().ToLower()==name.ToLower())
	                {
	                    comboBox.SelectedIndex = i;
	                    break;
	                }
	            }
	        }
	    }

	    private void PopulateTables(string connStr, string schemaName)
	    {
            this.cbo_Table.Items.Clear();
            string[] tblNames = DbUtil.GetTableNames(
                DataProviderType.MSSQL, schemaName, connStr);
            if (tblNames != null && tblNames.Length > 0)
            {
                foreach (string tblName in tblNames)
                    this.cbo_Table.Items.Add(tblName);
            }
	    }

	    /// <summary></summary>
		public void SaveSettings()
		{
		    DelimitedTextFileReaderInstruction instruction =
		        new DelimitedTextFileReaderInstruction(
		            this._TxtFileReaderComponent.ComponentID, Guid.Empty, this.txt_InputFile.Text,
		            new Delimiter((SpecialDelimiter) this.cbo_SpecialDelimiter.SelectedIndex,
		                          this.txt_DelimiterPattern.Text),
		            (int) this.num_ColHeaderRow.Value,
		            this.txt_Connection.Text, this.txt_Schema.Text,
		            this.cbo_Table.Text, this.ck_CreateNewTable.Checked, this.ck_ClearData.Checked);
			this._TxtFileReaderComponent.Instruction = instruction;
		}

		/// <summary></summary>
		public TestResult Test()
		{
			throw new System.NotImplementedException();
		}

		#endregion

		private void btn_AddColDefinition_Click(object sender, EventArgs e)
		{
			this.SaveSettings();
			DelimitedTextFileReaderWorker worker = new DelimitedTextFileReaderWorker();
			worker.SetInstruction(Guid.NewGuid(), this._TxtFileReaderComponent.Instruction, "Read delimited text file",
			                      this._TxtFileReaderComponent.ComponentName);
			worker.WorkerErredEvent += new WorkerHasError(worker_WorkerErredEvent);
			worker.WorkerFinishedEvent += new WorkerFinished(worker_WorkerFinishedEvent);
			DataTable dt = worker.Test(100);
			this.dv_Preview.DataSource = dt;
			this.dv_Preview.Refresh();
		}

		void worker_WorkerFinishedEvent(Guid ticketID, Type workerType, InstructionBase instructionBase, ResultBase resultBase)
		{
			
		}

		void worker_WorkerErredEvent(Guid ticketID, Type workerType, InstructionBase instructionBase, string error, bool isFatal)
		{
			MessageBox.Show(error);
		}

		private void cbo_SpecialDelimiter_SelectedIndexChanged(object sender, EventArgs e)
		{
			if(this.cbo_SpecialDelimiter.SelectedIndex>=0)
			{
				SpecialDelimiter specialDelimiter = (SpecialDelimiter) this.cbo_SpecialDelimiter.SelectedIndex;
				if(specialDelimiter==SpecialDelimiter.Other)
				{
					this.txt_DelimiterPattern.Enabled = true;
				}
				else
				{
					this.txt_DelimiterPattern.Text = string.Empty;
					this.txt_DelimiterPattern.Enabled = false;
				}
			}
		}

		private void btn_Cancel_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void btn_OK_Click(object sender, EventArgs e)
		{
			this.SaveSettings();
			if (this.UpdateComponentSettingEvent != null)
				this.UpdateComponentSettingEvent(this._ActivityNode, this._TxtFileReaderComponent);
			this.Close();
		}

		private void btn_Browse_Click(object sender, EventArgs e)
		{
			OpenFileDialog dlg=new OpenFileDialog();
			dlg.Filter = "Text files(*.csv;*.txt)|*.csv;*.txt|All files(*.*)|*.*";
			if(dlg.ShowDialog()==DialogResult.OK)
			{
				this.txt_InputFile.Text = dlg.FileName;
			}
		}

        private void btn_Refresh_Click(object sender, EventArgs e)
        {
            this.PopulateTables(this.txt_Connection.Text, this.txt_Schema.Text);
        }
	}
}
